

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;


public class MsgReceiver {

	public static void main(String[] argv)  {

		ConnectionFactory connfactory = new ConnectionFactory();
		connfactory.setHost("localhost");
		
		Connection conn = null;
		Channel channel = null;
		try {
			conn = connfactory.newConnection();
			conn.createChannel();
			channel = conn.createChannel();
			String qName = "MyQueue";
			channel.queueDeclare(qName, false, false, false, null);
			// 创建消费者
			Consumer consumer = new DefaultConsumer(channel) {
				@Override
				public void handleDelivery(String consumerTag, Envelope envelope,
						BasicProperties properties, byte[] msgBody)
						{					
					System.out.println("msg:"  + new String(msgBody) );
				}
			};
			channel.basicConsume(qName, true, consumer);
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
		}
		finally{
			// 关闭通道和连接
		    try {
		    	if(channel != null){
		    		channel.close();	
		    	}
				if(conn != null)
				{
					conn.close();	
				}			    
			} catch (IOException e) {
				e.printStackTrace();
			} catch (TimeoutException e) {
				e.printStackTrace();
			}			
		}
		
	}
}

